package com.viking.car;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Client {

    public static void main(String[] args) throws Exception {
        Socket socket = new Socket("192.168.2.1",7980);
        Token token = new Token();
        token.setType("1");
        token.setOrderNo("000000000F2014031812000814648141");
        token.setUserId("0907e7826f744542b492bbd3596439db");
        token.setCarId("WBA3A5507CNN00000");
        token.setOrderStartDt("20140319083000");
        token.setOrderStartDtOff("0900");
        token.setOrderEndDt("20140319083000");
        token.setOrderEndDtOff("0900");
        executeCommand2("192.168.2.1",7980,token.toString(),1, Constants.TAKE_CAR);
//        socket = new Socket("localhost",7981);
//        executeCommand(socket,"token",1, Constants.OPEN_DOOR);
//        socket = new Socket("localhost",7981);
//        executeCommand(socket,"token",1, Constants.LOCK_DOOR);
//        socket = new Socket("localhost",7981);
//        executeCommand(socket,"token",1, Constants.RETURN_CAR);
    }

    public static Message executeCommand(Socket socket,String token,int sequenceId,int commandId){
        OutputStream ops = null;
        InputStream ins = null;
        try {
            ops = socket.getOutputStream();
            ins = socket.getInputStream();
            Message message = MessageUtils.generateMessage(token,commandId,sequenceId,false);
            byte[] bytes = MessageUtils.messageToBytes(message);
            /* */
            FileOutputStream fos = new FileOutputStream("d:\\temp.txt");
            fos.write(bytes,0,bytes.length);//写到文件中，作为对比
            fos.flush();
            fos.close();
            ops.write(bytes,0,bytes.length);
            ops.flush();
            socket.shutdownOutput();  //关闭输出流
            System.out.println("客户端发送消息结束！");

            //接收服务端的响应
            byte[] respBytes = MessageUtils.readMessageBytes(ins);
            Message resp = MessageUtils.bytesToMessage(respBytes,true);
            System.out.println("响应消息是："+resp);
            return resp;
        }catch (Exception e){
            e.printStackTrace();
            //重试
        } finally {
            MessageUtils.close(ins);
            MessageUtils.close(ops);
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }



    public static Message executeCommand2(String host,int port,String token,int sequenceId,int commandId){
        try{
            SocketAddress address = new InetSocketAddress(host,port);
            SocketChannel client=SocketChannel.open(address);
            client.configureBlocking(false);
            Message req = MessageUtils.generateMessage(token,commandId,sequenceId,false);
            byte[] bytes = MessageUtils.messageToBytes(req);
            writeToFile(bytes,"d:\\req.txt");
            ByteBuffer buffer=ByteBuffer.wrap(bytes);
            buffer.clear();
            int d=client.write(buffer);
            System.out.println("发送数据: "+req);
            ByteBuffer respBuffer  = null;
            if (commandId == Constants.QUERYPOWER){
                respBuffer = ByteBuffer.allocate(32);   //查询电量多了两个字节
            }else {
                respBuffer = ByteBuffer.allocate(30);
            }
            int cnt = 300;
            while(true){
                int i=client.read(respBuffer);
                if(i>0){
                    byte[] b=respBuffer.array();
                    writeToFile(b,"d:\\resp.txt");
                    Message resp = MessageUtils.bytesToMessage(b,true);
                    System.out.println("接收数据: "+resp);
                    client.close();
                    System.out.println("连接关闭!");
                    respBuffer.flip();
                    return resp;
                }
                Thread.sleep(100); //
                if (cnt == 0){
                    System.out.println("没收到响应");
                    break;
                }
                cnt --;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    //写到文件中，作为对比
    private static void writeToFile(byte[] bytes,String fileName) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            fos.write(bytes, 0, bytes.length);
            fos.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
